package com.cai.dao.impl;

import com.cai.dao.GoodsDao;
import com.cai.dao.LogDao;
import com.cai.entity.LogItem;
import com.cai.util.C3p0Util;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author RuoLi
 * 日志接口实现类
 */
public class LogDaoImpl implements LogDao {
    static QueryRunner runner = new QueryRunner(C3p0Util.getDataSource());

    @Override
    public int logSend(LogItem logItem) {
        String sql = "INSERT INTO log(user_name,user_email,user_type,item_name,log_sendTime,log_send_num,log_status) VALUES (?, ?, ?, ?, ?,?, 0)";
        Object[] args = {logItem.getUser_name(), logItem.getUser_email(), logItem.getUser_type(),
                logItem.getItem_name(), logItem.getLog_sendTime(), logItem.getLog_send_num(),};
        //减少物品数量
        GoodsDao goodsDao = new GoodsDaoImpl();
        goodsDao.sendItem(Integer.parseInt(logItem.getLog_send_num()), logItem.getItem_name());
        //没有验证
        return logSendAndReturn(sql, args);

    }

    @Override
    public int logReturn(LogItem logItem) {
        String sql = "UPDATE log SET log_returnTime =?,log_return_num = ?,log_status=1 WHERE user_name=? AND item_name=? AND user_email=?";
        Object[] args = {logItem.getLog_returnTime(), logItem.getLog_return_num(), logItem.getUser_name(), logItem.getItem_name(), logItem.getUser_email()};
        GoodsDao goodsDao = new GoodsDaoImpl();
        goodsDao.returnItem(Integer.parseInt(logItem.getLog_return_num()), logItem.getItem_name());
        //没有验证
        return logSendAndReturn(sql, args);

    }

    @Override
    public List<LogItem> listLogItems() {
        List<LogItem> logItems = new ArrayList<>();
        String sql = "select * from log";
        try {
            logItems = runner.query(sql, new BeanListHandler<>(LogItem.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return logItems;
    }

    private int logSendAndReturn(String sql, Object[] params) {
        try {
            int code = runner.update(sql, params);
            if (code != 0) {
                return 1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
